﻿// MIT License
//
// Copyright (c) 2021-present zuohuaijun, Daming Co.,Ltd and Contributors
//
// 电话/微信：18020030720 QQ群1：87333204 QQ群2：252381476

using Admin.NET.Application.Const;
using Admin.Net.InformationPlatform.Entity;
using Microsoft.AspNetCore.Mvc;
using Nest;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion.DynamicApiController;
using Furion.DependencyInjection;
using Admin.NET.Core.Service;
using Admin.NET.Core;
using System.ComponentModel;
using Admin.Net.InformationPlatform.Service.SRM.Dto;
using iTextSharp.text.pdf.parser.clipper;
using Furion.FriendlyException;
using Microsoft.Office.Interop.Word;

namespace Admin.Net.InformationPlatform.Service.SRM
{
    /// <summary>
    /// SRM管理
    /// </summary>
    [ApiDescriptionSettings(groups: "SRM", Name = "页面布局管理", Tag = "页面布局管理", Order = 200)]

    public class SRMPAGELAYOUTService : IDynamicApiController, ITransient
    {
        /// <summary>
        /// 单例数据链接
        /// </summary>
        ISqlSugarClient db;
        /// <summary>
        /// T100数据库
        /// </summary>
        private SqlSugarProvider _T100Db;
        private SqlSugarProvider _SjDb;
        private SqlSugarProvider _plm;
        private SqlSugarProvider _Dilon;


        /// <summary>
        /// 用户信息
        /// </summary>
        TokenUser _User;
        /// <summary>
        /// 成品仓库管理模块
        /// </summary>
        /// <param name="db"></param>
        public SRMPAGELAYOUTService(ISqlSugarClient db)
        {
            this.db = db;
            this._T100Db = this.db.AsTenant().GetConnection(T100Const.ConfigId);
            this._SjDb = this.db.AsTenant().GetConnection(SJDB.ConfigId);
            this._plm = this.db.AsTenant().GetConnection(PLM.ConfigId);
            this._Dilon = this.db.AsTenant().GetConnection(Dilon.ConfigId);
            // 获取 `Jwt` 存储的信息 企业编号与据点信息
            _User = Util.SjCommonUtil.GetT100UserTokenInfo(_T100Db, _Dilon);

        }

        /// <summary>
        /// 获取页面布局
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [DisplayName("获取页面布局")]
        [HttpPost("/SRM/GetPageLayoutList")]
        public async Task<List<SrmPageLayoutOutput>> GetPageLayoutList(SrmPageLayoutInput input)
        {
            return  await _SjDb.Queryable<SRM_PAGE_LAYOUT>()
            .Where(l => l.USERID == _User.UserId)
            .Where(l => l.OWNINGPAGE == input.OWNINGPAGE)

.OrderBy(l => l.SORT) //排序号排序
.Select(l => new SrmPageLayoutOutput
{
    
    PROP = l.COLUMNCODE,
    LABEL = l.COLUMNNAME,
    ISCHECK = l.ISSHOW==1?true:false,
    HEADERALIGN = l.HEADERALIGN,
    HIDECHECK = l.HIDECHECK == 1 ? true : false,
    WITH = l.WITHS,
    SORTABLE = l.SORTABLE,
    TOOLTIP = l.TOOLTIP == 1 ? true : false,

}).ToListAsync();

        }
        /// <summary>
        /// 保存页面布局
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [DisplayName("保存页面布局")]
        [HttpPost("/SRM/AddPageLayout")]
        public async Task<string> AddPageLayout(SrmPageLayoutAdd[] input)
        {
            if (input.Length > 0)
            {
                await _SjDb.Deleteable<SRM_PAGE_LAYOUT>().Where(e =>e.USERID == _User.UserId && e.OWNINGPAGE == input[0].OWNINGPAGE).ExecuteCommandAsync();
                List<SRM_PAGE_LAYOUT> pagelayoutlist = new List<SRM_PAGE_LAYOUT>();
                for (int i = 0; i < input.Length; i++)
                {
                    SRM_PAGE_LAYOUT pagelayout = new SRM_PAGE_LAYOUT()
                    {
                        ID= Guid.NewGuid().ToString("N"),
                        COLUMNCODE = input[i].PROP,//页面code
                        COLUMNNAME = input[i].LABEL,//页面名称
                        SORT = input[i].SORT,//排序号
                        USERID  =_User.UserId,//所属人
                        OWNINGPAGE  = input[i].OWNINGPAGE,//所属页面
                        ISSHOW = Convert.ToInt32(input[i].ISCHECK),//是否展示
                        CREATETIME  =DateTime.Now,//创建时间
                        ISDELETE  = 0,//伪删除
                        HEADERALIGN = input[i].HEADERALIGN,
                        HIDECHECK = Convert.ToInt32(input[i].HIDECHECK),
                        WITHS = input[i].WITH,
                        SORTABLE = input[i].SORTABLE,
                        TOOLTIP = Convert.ToInt32(input[i].TOOLTIP)
                    };
                    pagelayoutlist.Add(pagelayout);
                }
                #region 插入事务
                try
                {
                    //开启事务
                    _SjDb.Ado.BeginTran();
                    int cnt = await _SjDb.Insertable<SRM_PAGE_LAYOUT>(pagelayoutlist).ExecuteCommandAsync();
                    if (cnt == 0)
                    {
                        throw Oops.Oh($"新建任务失败！");
                    }
                    //提交事务
                    _SjDb.Ado.CommitTran();
                    return "插入成功";
                }
                catch (Exception e)
                {
                    //回滚事务
                    _SjDb.Ado.RollbackTran();
                    throw Oops.Oh($"异常：{e.Message}");
                }
                #endregion
            }
            return "成功";
        }

    }
}